package com.fernandomdo.ServiceAdministrator;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.fernandomdo.ServiceAdministrator.Territory.TerritoryListItem;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface.DatabaseConstants;

public class InfoTerritoryFragment extends Fragment {
	public static final String TAG = "InfoViewFragment";
	
	private Context appContext;
	private static View view;
	public static DatabaseInterface databaseInterface;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		appContext = getActivity().getApplicationContext();
		databaseInterface = new DatabaseInterface(appContext);		
	}
		
	@Override
	public void onPause() {
		super.onPause();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		//databaseInterface.readableDB.close();
	}
	
	/**
	 * Called when the info needs to be updated to the currently selected item. Passing an object has some advantages
	 * <p>1) It allows us to have the information related to the list while also permitting us to access other info stored in a separate table
	 * @param item
	 */
	public void updateInfo(Object item) {
		TextView name 				= (TextView)view.findViewById(R.id.territory_name);	
		TextView description 		= (TextView)view.findViewById(R.id.description_text);
		TextView currentBorrower 	= (TextView)view.findViewById(R.id.borrower_name);
		TextView lastBorrower 		= (TextView)view.findViewById(R.id.last_borrower_name);
		TextView timesPerMonth 		= (TextView)view.findViewById(R.id.borrowed_per_month_count);
		TextView timesPerYear 		= (TextView)view.findViewById(R.id.borrowed_per_year_count);
		TextView lastCheckIn 		= (TextView)view.findViewById(R.id.date_returned);
		TextView lastCheckOut 		= (TextView)view.findViewById(R.id.date_borrowed);	
		
		if(item instanceof TerritoryListItem) {
			Cursor cursor = null;
			try {
				cursor = new InfoTerritoryFragment.TerritoryInfoLoader().execute(((TerritoryListItem) item).id).get();
			}							
			catch (InterruptedException e) {
				e.printStackTrace();
			} 
			catch (ExecutionException e) {
				e.printStackTrace();
			}
			//update all of the TextViews
			if(cursor.getCount() > 0) {
				//TODO: pass te cursor to an instance of TerritoryInfo, and let that sort out all of the info into containers which we can use later
				cursor.moveToFirst();
				name.setText(((TerritoryListItem)item).name);
				description.setText(cursor.getString(cursor.getColumnIndex(DatabaseConstants.DESCRIPTION)));
				
				String sCurrentBorrower = cursor.getString(cursor.getColumnIndex(DatabaseConstants.CURRENT_BORROWER));
				if(sCurrentBorrower.equals("-1"))
					currentBorrower.setText(getResources().getString(R.string.no_borrower));
				else
					currentBorrower.setText(sCurrentBorrower);
					
				
				String sLastBorrower = cursor.getString(cursor.getColumnIndex(DatabaseConstants.LAST_BORROWER));
				if(sLastBorrower.equals("-1"))
					currentBorrower.setText(getResources().getString(R.string.no_borrower));
				else
					lastBorrower.setText(sLastBorrower);
				
				
				
				int nTimesPerMonth = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.TIMES_BORROWED_MONTH));
				if(nTimesPerMonth < 0)
					timesPerMonth.setText(getResources().getString(R.string.never_checked_out));
				else
					timesPerMonth.setText(String.valueOf(nTimesPerMonth));
				
				int nTimesPerYear = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.TIMES_BORROWED_YEAR));
				if(nTimesPerYear < 0)
					timesPerYear.setText(getResources().getString(R.string.never_checked_out));
				else
					timesPerYear.setText(cursor.getString(cursor.getColumnIndex(DatabaseConstants.TIMES_BORROWED_YEAR)));
				
				lastCheckIn.setText(cursor.getString(cursor.getColumnIndex(DatabaseConstants.DATE_IN)));
				lastCheckOut.setText(cursor.getString(cursor.getColumnIndex(DatabaseConstants.DATE_OUT)));
			}
		}
		else {
			Log.d(TAG, "item passed in was null!");
			name.setText(getResources().getString(R.string.no_item_selected));
			
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View parent = inflater.inflate(R.layout.territory_info, container, false);
		view = parent;
		return parent;
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//InfoSorter
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private class TerritoryInfoSorter {
	public String currentInPossesion;
	public String lastInPossesion;
	public String amountBorrowed;
	public String lastDateIn;
	public String lastDateOut;

	private Cursor publisherInfo;
	private ArrayList<Cursor> borrowedTerritories;
	private long idOfCurrent;
	private long idOfLast;

	public TerritoryInfoSorter(Cursor publisherInfo) {
		this.publisherInfo = publisherInfo;
		sortInfo();
	}

	private void sortInfo() {
		if(publisherInfo.moveToFirst()) {
			idOfLast 	= publisherInfo.getLong(publisherInfo.getColumnIndex(DatabaseConstants.CURRENT_IN_POSSESION));
			idOfCurrent = publisherInfo.getLong(publisherInfo.getColumnIndex(DatabaseConstants.LAST_IN_POSSESION));
			
			try {
				borrowedTerritories = new PublisherLoader().execute(idOfCurrent, idOfLast).get();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			catch (ExecutionException e) {
				e.printStackTrace();
			}
			
			//Current Territory
			Cursor current = borrowedTerritories.get(0);
			if(current.moveToFirst()) {
				currentInPossesion = current.getString(current.getColumnIndex(DatabaseConstants.TERRITORY));    				
			}
			else {
				currentInPossesion = appContext.getResources().getString(R.string.no_territory);
			}

			//Current Territory
			Cursor last = borrowedTerritories.get(1);
			if(last.moveToFirst()) {
				lastInPossesion = last.getString(current.getColumnIndex(DatabaseConstants.TERRITORY));    				
			}
			else {
				lastInPossesion = appContext.getResources().getString(R.string.no_territory);
			}

			amountBorrowed 	= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.AMOUNT_BORROWED));
			lastDateIn		= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.LAST_DATE_IN));
			lastDateOut		= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.LAST_DATE_OUT));        	
		}
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Async loaders to get the items from the database
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	* Simple Loader to retrieve the Territory Info
	*/
	private static class TerritoryInfoLoader extends AsyncTask<Long, Integer, Cursor> {
		@Override
		protected Cursor doInBackground(Long... ids) {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			Cursor cursor;
			
			final String[] FROM = { DatabaseConstants.TERRITORY_ID, DatabaseConstants.DESCRIPTION, DatabaseConstants.CURRENT_BORROWER, 
					DatabaseConstants.LAST_BORROWER, DatabaseConstants.TIMES_BORROWED_MONTH, DatabaseConstants.TIMES_BORROWED_YEAR, 
					DatabaseConstants.DATE_IN, DatabaseConstants.DATE_OUT};
			final String SELECTION = DatabaseConstants.TERRITORY_ID + '=' + ids[0];
			cursor = databaseInterface.readableDB.query(DatabaseConstants.TERRITORY_INFO_TABLE,  FROM, SELECTION, null, null, null, null);
			//return db.rawQuery("SELECT rowid _id,name,strftime('%s',started), strftime('%s', finished) FROM territory ORDER BY started DESC", new String[] {});
			//databaseInterface.readableDB.close();
			return cursor;
	     }
	}
	
	/**
	* Simple Loader to retrieve the Publisher Info
	*/
	private class PublisherLoader extends AsyncTask<Long, Integer, ArrayList<Cursor>> {
		@Override
		protected ArrayList<Cursor> doInBackground(Long... ids) {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			
			ArrayList<Cursor> cursors = new ArrayList<Cursor>();
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.TERRITORY };
			String SELECTION = BaseColumns._ID + '=' + ids[0];
			
			for(int i=0; i<ids.length; i++) {
				SELECTION = BaseColumns._ID + '=' + ids[i];
				Cursor cursor = databaseInterface.readableDB.query(DatabaseConstants.TERRITORY_TABLE,  FROM, SELECTION, null, null, null, null);
				cursors.add(cursor);
			}
			//return db.rawQuery("SELECT rowid _id,name,strftime('%s',started), strftime('%s', finished) FROM territory ORDER BY started DESC", new String[] {});
			return cursors;
	     }
	}

	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ViewHolders
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	static class TerritoryInfoHolder {
        TextView description;
        TextView current_borrower;
        TextView last_borrower;
        TextView times_borrowed_month;
        TextView times_borrowed_year;
        TextView date_in;
        TextView date_out;
        
        public TerritoryInfoHolder(View base) {
        	description = (TextView)base.findViewById(R.id.description_text);
        	//status = (TextView)base.findViewById(R.id.territory_item_status);
        }
    }
}